package com.rankeiot.core.dict;

import com.rankeiot.core.data.Pair;
import com.rankeiot.core.data.Item;
import com.rankeiot.core.util.LocaleUtil;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 固定字典管理
 */
@SuppressWarnings("AlibabaConstantFieldShouldBeUpperCase")
public class FixedDictManager {
    private static final Map<String, Pair<String, List<Item>>> fixedDictMap = new ConcurrentHashMap<>();

    public static void regFixedDict(Class<? extends Enum> fixedDictClass) {
        String dictName = fixedDictClass.getSimpleName();
        Pair<String, List<Item>> fixedDict = fixedDictMap.get(dictName);
        if (fixedDict == null) {
            Title note = fixedDictClass.getAnnotation(Title.class);
            String title = dictName;
            if (note != null) {
                title = LocaleUtil.encode(note.value(),note.en());
            }
            fixedDict = new Pair<>(title, new ArrayList<>());
            fixedDictMap.put(dictName, fixedDict);
        }
        List<Item> items = fixedDict.getValue();
        Field[] fields = fixedDictClass.getDeclaredFields();
        for (Field f : fields) {
            if (!f.isEnumConstant()) {
                continue;
            }
            String name = f.getName();
            String title = name;
            if (IFixedDict.class.isAssignableFrom(f.getType())) {
                try {
                    IFixedDict item = (IFixedDict) f.get(fixedDictClass);
                    name = item.getValue();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            if (ITitleFixedDict.class.isAssignableFrom(f.getType())) {
                try {
                    ITitleFixedDict item = (ITitleFixedDict) f.get(fixedDictClass);
                    title =  LocaleUtil.encode(item.getTitle(),item.getEn());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }else{
                Title titleNote = f.getAnnotation(Title.class);
                if (titleNote != null) {
                    title =  LocaleUtil.encode(titleNote.value(),titleNote.en());
                }
            }
            items.add(new Item(name, title));
        }
    }

    public static List<Item> getDict(String name) {
        Pair<String, List<Item>> e = fixedDictMap.get(name);
        if (e == null) {
            return new ArrayList<>();
        }
        return e.getValue();
    }

    public static Map<String, Pair<String, List<Item>>> getFixedDictMap() {
        return fixedDictMap;
    }
}
